from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
# 生成RSA私钥，密钥长度为2048位
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
# 将私钥序列化为PEM格式
pem_private_key = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)
print("私钥（PEM格式）:", pem_private_key.decode())
# 从私钥获取公钥
public_key = private_key.public_key()
# 将公钥序列化为PEM格式
pem_public_key = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print("公钥（PEM格式）:", pem_public_key.decode())